package com.alita.redis.utils.dingding.entity;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class DingtalkChatbotClient {

    private static final Logger LOG = LoggerFactory.getLogger(DingtalkChatbotClient.class);

    private DingtalkChatbotClient() {

    }

    private static HttpClient httpclient = HttpClients.createDefault();

    public SendResult send(String webhook, Message message) {
        SendResult sendResult = new SendResult();
        try {
            HttpPost httppost = new HttpPost(webhook);
            httppost.addHeader("Content-Type", "application/json; charset=utf-8");
            StringEntity se = new StringEntity(message.toJsonString(), "utf-8");
            httppost.setEntity(se);

            HttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(response.getEntity());
                JSONObject obj = JSONObject.parseObject(result);

                Integer errcode = obj.getInteger("errcode");
                sendResult.setErrorCode(errcode);
                sendResult.setErrorMsg(obj.getString("errmsg"));
                sendResult.setIsSuccess(errcode.equals(0));
            }
        } catch (Exception e) {
            LOG.error("Send Dingtalk error, webhook = " + webhook + ", message = " + message, e);
            sendResult.setIsSuccess(false);
            sendResult.setErrorMsg(e.getMessage());
        }
        return sendResult;
    }

    private static class SingletonHolder {
        private static DingtalkChatbotClient instance = new DingtalkChatbotClient();
    }

    public static DingtalkChatbotClient getInstance() {
        return SingletonHolder.instance;
    }

}


